package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.entity.QueryPageBean;
import com.itheima.mapper.MenuMapper;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.List;

import java.util.*;


@Service
@Transactional
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {
    @Override
    public Set<Menu> getMenusByUsername(String username) {
        List<Integer> roleIds = baseMapper.findRoleIdsByUsername(username);
        Set<Menu> menus = new HashSet<>();
        for (Integer roleId : roleIds) {
            List<Menu> menuList = baseMapper.findMenusByRoleId(roleId);
            for (Menu menu : menuList) {
                Integer menuId = menu.getId();
                List<Menu> childrenMenuList = baseMapper.findChildrenMenus(roleId,menuId);
                menu.setChildren(childrenMenuList);
            }
            menus.addAll(menuList);
        }
        return menus;
    }

    public Map findPage(QueryPageBean queryPageBean){
        QueryWrapper<Menu> QueryWrapper = new QueryWrapper<>();
        String queryString = queryPageBean.getQueryString();
        QueryWrapper.like("name",queryString==null?"":queryString);
        Page<Menu> page = page(new Page<Menu>(queryPageBean.getCurrentPage(), queryPageBean.getPageSize()), QueryWrapper);
        HashMap<String, Object> map = new HashMap<>();
        map.put("total",page.getTotal());
        map.put("list",page.getRecords());
        return map;
    }

    @Override
    public List<Menu> findAll( ) {
        return baseMapper.selectList(null);
    }


}
